package com.ssm.juc.executors;


import java.util.concurrent.*;

public class ThreadPoolRejectedPolicyTest {
    private static ThreadFactory namedThreadFactory = new ThreadFactory() {
        int i = 0;

        @Override
        public Thread newThread(Runnable r) {
            return new Thread(r, "run-thread-[" + (i++) + "]");
        }
    };
    private static ExecutorService threadPool = new
            ThreadPoolExecutor(2,
            2, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue(2), namedThreadFactory, new
            // 1. 丢弃任务并抛出RejectedExecutionException异常，默认策略。
            ThreadPoolExecutor.AbortPolicy());
    // 2. 丢弃任务，但是不抛出异常。
    //ThreadPoolExecutor.DiscardPolicy());
    // 3. 丢弃队列中最前⾯的任务，然后重新尝试执⾏任务
    //ThreadPoolExecutor.DiscardOldestPolicy());
    // 4. 由调⽤线程处理该任务。
    //ThreadPoolExecutor.CallerRunsPolicy());
    // 5. 自定义模式
            /*
            RejectedExecutionHandler() {

                @Override
                public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                    //todo 发送告警提醒
                    System.out.println("send system alarm message to system admin");
                    //兜底处理，调用线程执行
                    if (!executor.isShutdown()) {
                        r.run();
                    }
                }
            });
             */

    public static void main(String[] args) {
        for (int i = 0; i < 10; i++) {
            int taskId = i;
            try {
                threadPool.execute(() -> {
                    try {
                        System.out.println(Thread.currentThread() + " taskId: " + taskId + " ----> thread execute ...");
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            } catch (RejectedExecutionException ree) {
                ree.printStackTrace();
            }
        }
        // 测试异常

        threadPool.shutdown();
        while (!threadPool.isTerminated()) {
        }
    }
}
